//公共js,以及基本方法封装 nvue里使用

/**
 * 获取请后台服务时的头信息
 */
import Java110Context from '../context/Java110Context.js'
function wxuuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid
}
const getDateYYYYMMDDHHMISS = function () {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  if (month < 10) {
    month = '0' + month;
  }
  if (day < 10) {
    day = '0' + day;
  }
  if (hour < 10){
    hour = '0'+hour;
  }
  if (minute < 10){
    minute = '0' + minute;
  }
  if (second < 10) {
    second = '0' + second;
  }
  return year + "" + month + "" + day + "" + hour + "" + minute + "" + second;
}

const getHeaders = function() {
  return {
    'app-id': '992019111758490006',
    'transaction-id': wxuuid(),
    'req-time': getDateYYYYMMDDHHMISS(),
    sign: '1234567',
    'user-id': '-1',
    // cookie: '_java110_token_=' + wx.getStorageSync('token')
  }
}

const fetch = {
	interfaceUrl: function() {
		//接口地址
		return "/api/";
	},
	logout(data){
	  if(data.indexOf('<!DOCTYPE html>') !== -1){
	  	uni.reLaunch({
	  		url:'/pages/login/login'
	  	})
	  }
	},
	toast: function(tips) {
		uni.showToast({
			title: tips || "出错啦~",
			icon: 'none',
			duration: 2000
		})
	},
	request: function(url, postData, method, type, showLoading) {
		//接口请求
		if (showLoading) {
			uni.showLoading({
				mask: true,
				title: '请稍候...'
			})
		}
		const token = postData.token || "";
		delete postData["token"]
		const params = {
			...postData 
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: fetch.interfaceUrl() + url,
				data: method === "POST" ? params : params,
				header: {
					'content-type': type ? 'application/x-www-form-urlencoded' : 'application/json',
					'cookie': token,
					'security': "1",
					...Java110Context.getHeaders()
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					if (res.statusCode != 200) {
						fetch.toast(res.data)
						reject(res)
						return;
					}
					showLoading && uni.hideLoading()
					fetch.logout(res.data)
					resolve(res.data)
				},
				fail: (res) => {
					fetch.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	}
}

module.exports = {
	request: fetch.request,
	toast: fetch.toast
}
